package cn.itcast.web.servlet;

import cn.itcast.daomain.PageBean;
import cn.itcast.daomain.commodity;
import cn.itcast.service.RouteService;
import cn.itcast.service.impl.RouteServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/routeServlet")
public class RouteServlet extends HttpServlet {
    private RouteService routeService=new RouteServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageSizeStr=request.getParameter("pageSize");
        String currentPageStr=request.getParameter("currentPage");
        String cid=request.getParameter("classid");

        //默认classid=0就是全部商品
        int classid=0;
        if (cid!=null&&cid.length()>0){
            classid=Integer.parseInt(cid);
        }else {
            classid=0;
        }

        //默认当前页码
        int currentPage=0;
        if (currentPageStr!=null&&currentPageStr.length()>0){
            currentPage=Integer.parseInt(currentPageStr);
        }else {
            currentPage=1;
        }

        //每页显示条数
        int pageSize=0;
        if (pageSizeStr!=null&&pageSizeStr.length()>0){
            pageSize=Integer.parseInt(pageSizeStr);
        }else {
            pageSize=12;
        }

        //调用service查询
        PageBean<commodity> pb = routeService.pageQuery(classid,currentPage, pageSize);
        //写回jsp
        ObjectMapper mapper=new ObjectMapper();
        String json=mapper.writeValueAsString(pb);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().append(json);
    }
}
